<?php

class RegisterForm extends CFormModel
{
    public $name;
    public $password;
    public $passwordRepeat;
    public $verifyCode;
    
    public function rules()
    {
        return array(
            array('name,password,passwordRepeat,verifyCode','required'),
            array('password','compare','compareAttribute'=>'passwordRepeat'),
            array('verifyCode','validateVerifyCode'),
        );
    }
    
    public function attributeLabels()
    {
        return array(
            'name' => '用户名',
            'password' => '密码',
            'passwordRepeat' => '密码确认',
            'verifyCode'=>'验证码'
        );
    }

    public function validateVerifyCode($object,$attribute)
    {
        if(!$this->hasErrors())
        {
            $sessionName=VerifyImage::getSessionName('register');
            $code = Yii::app()->session->itemAt($sessionName);
            Yii::app()->session->remove($sessionName);
        
            if(!isset($this->verifyCode)) {
                $this->addError('verifyCode', $this->getAttributeLabel('verifyCode').'不能为空');
                return false;                                        
            }
            if($this->verifyCode!==$code){
                $this->addError('verifyCode', $this->getAttributeLabel('verifyCode').'错误');
                return false;        
            }
            return true;
        }
    }
}

class RegisterAction extends CAction
{
	private $_form;
	private $_user;

	private function createUser()
	{
		$this->_user=new User;
		$this->_user->scenario='create';
        $this->_user->name=$this->_form->name;  
		$this->_user->password=$this->_form->password;
        if(!$this->_user->validate()){
            $this->_form->addErrors($this->_user->getErrors());
            return false;
        }
        
        $this->_user->registerIp=Yii::app()->request->userHostAddress;
        $this->_user->registerTime=time();
        $this->_user->lastLoginIp=$this->_user->registerIp;
        $this->_user->lastLoginTime=$this->_user->registerTime;
		if(!User::saveObject($this->_user)) {
            $this->_form->addErrors($this->_user->getErrors());
            return false;
        }
        
        return true;
	}

	private function renderView()
	{
		$this->getController()->render('register',
			array(
				'form'=>$this->_form,
			)
		);
	}

    public function run()
    {
		$this->_form=new RegisterForm;
		if(!isset($_POST['RegisterForm'])){
			$this->renderView();
			return;
		}

		$this->_form->attributes=$_POST['RegisterForm'];
		if(!$this->_form->validate()){
			$this->renderView();
			return;
		}

		if(!$this->createUser()){
			$this->renderView();
            return;
		}

		$identity=new UserIdentity($this->_user->id, $this->_user->name,$this->_user->password);
		Yii::app()->user->login($identity);
        $this->controller->redirect(array('/kitchen/show'));
    }
}

?>
